package com.example.area.io.netty.nio.channel;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * @author kancy
 * @date 2019/2/23 17:16
 */
public class FileChannelDemo {
	public static void main(String[] args) {


		String filePath = "C:/nio.data";
//		write(filePath);
		Path path = Paths.get(filePath);
		try {
			FileChannel channel = FileChannel.open(path);
			ByteBuffer byteBuffer = ByteBuffer.allocate(128);
			channel.read(byteBuffer);
			byteBuffer.flip();

			int anInt = byteBuffer.getInt();
			System.out.println(anInt);

			channel.close();

		} catch (IOException e) {
			e.printStackTrace();
		}

	}

	private static void write(String filePath) {
		File file = new File(filePath);
		try {
			FileOutputStream fileOutputStream = new FileOutputStream(file);
			FileChannel channel = fileOutputStream.getChannel();

			ByteBuffer byteBuffer = ByteBuffer.allocate(128);

			byteBuffer.putInt(1).putInt(2).putInt(3).flip();
			channel.write(byteBuffer);
			byteBuffer.clear();

			byteBuffer.putInt(4).putInt(5).putInt(6).flip();
			channel.write(byteBuffer);
			byteBuffer.clear();

			channel.close();
			fileOutputStream.close();

		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
